package org.vt.ece4564.pcw.textinclass;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.util.Log;

public class UploadMessageTask extends AsyncTask<Void, Void, Void> {
	
	private Cookie cookie_;
	private String number_;
	private String message_;
	
	private final String URL = "http://pcw-textinclass.appspot.com/postMessagesAndroid";
	
	UploadMessageTask(Cookie cookie, String number, String message) {
		cookie_ = cookie;
		number_ = number;
		message_ = message;
	}

	@Override
	protected Void doInBackground(Void... arg0) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(URL);
			
			post.addHeader("Cookie", cookie_.getName() + "=" + cookie_.getValue());
			
			List<NameValuePair> data = new ArrayList<NameValuePair>();
			
			data.add(new BasicNameValuePair("from_number", number_));
			data.add(new BasicNameValuePair("message", message_));
			
			HttpEntity entity = new UrlEncodedFormEntity(data);
			
			post.setEntity(entity);
			
			HttpResponse response = client.execute(post);
			
			if (response.getStatusLine().getStatusCode() != 200) {
				Log.d("UploadMessageTaskError", response.getStatusLine().toString());
				return null;
			}
			
			String line;
			String responseString = "";
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			
			while ((line = reader.readLine()) != null) {
				responseString += line;
			}
			
			Log.d("UploadMessageTask", responseString);
			
		} catch(Exception e) {
			Log.d("UploadMessageTaskException", e.toString());
		}
		return null;
	}

}
